<template>
  <div
    class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 border border-gray-100 dark:border-gray-700"
  >
    <div class="mb-6">
      <label
        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >标题</label
      >
      <input
        v-model="title"
        type="text"
        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
        placeholder="输入文章标题"
      />
    </div>

    <div class="mb-6">
      <label
        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
        >描述</label
      >
      <textarea
        v-model="description"
        rows="2"
        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
        placeholder="输入文章描述"
      ></textarea>
    </div>

    <div class="mb-6">
      <div class="flex justify-between items-center mb-2">
        <label
          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
          >内容</label
        >
        <div class="flex space-x-2">
          <button
            @click="previewMode = !previewMode"
            class="px-3 py-1 text-sm rounded-md transition-colors"
            :class="
              previewMode
                ? 'bg-blue-100 text-blue-600'
                : 'bg-gray-100 text-gray-600'
            "
          >
            {{ previewMode ? "编辑" : "预览" }}
          </button>
        </div>
      </div>
      <div v-if="!previewMode" class="relative">
        <textarea
          v-model="content"
          rows="20"
          class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white font-mono"
          placeholder="使用 Markdown 编写文章内容"
        ></textarea>
      </div>
      <div
        v-else
        class="prose prose-lg max-w-none dark:prose-invert p-4 border border-gray-300 dark:border-gray-600 rounded-md"
      >
        <ContentRenderer :value="{ body: content }" />
      </div>
    </div>

    <div class="flex justify-end space-x-4">
      <button
        @click="saveAsDraft"
        class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"
      >
        保存草稿
      </button>
      <button
        @click="publish"
        class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700"
      >
        发布文章
      </button>
    </div>
  </div>
</template>

<script setup>
const title = ref("");
const description = ref("");
const content = ref("");
const previewMode = ref(false);

// 生成文件名
const generateFileName = () => {
  const date = new Date().toISOString().split("T")[0];
  const slug = title.value
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/(^-|-$)/g, "");
  return `${date}-${slug}.md`;
};

// 生成 Markdown 内容
const generateMarkdown = () => {
  return `---
title: "${title.value}"
description: "${description.value}"
date: "${new Date().toISOString().split("T")[0]}"
---

${content.value}`;
};

// 保存草稿
const saveAsDraft = async () => {
  if (!title.value || !content.value) {
    alert("请填写标题和内容");
    return;
  }

  try {
    const fileName = generateFileName();
    const markdown = generateMarkdown();

    // 调用 API 保存文件
    const response = await fetch("/api/blog/save", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        fileName,
        content: markdown,
      }),
    });

    if (response.ok) {
      alert("草稿保存成功");
    } else {
      throw new Error("保存失败");
    }
  } catch (error) {
    console.error("保存失败:", error);
    alert("保存失败，请重试");
  }
};

// 发布文章
const publish = async () => {
  if (!title.value || !content.value) {
    alert("请填写标题和内容");
    return;
  }

  try {
    const fileName = generateFileName();
    const markdown = generateMarkdown();

    // 调用 API 保存文件
    const response = await fetch("/api/blog/publish", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        fileName,
        content: markdown,
      }),
    });

    if (response.ok) {
      alert("文章发布成功");
      // 跳转到文章页面
      navigateTo(`/blog/${fileName.replace(".md", "")}`);
    } else {
      throw new Error("发布失败");
    }
  } catch (error) {
    console.error("发布失败:", error);
    alert("发布失败，请重试");
  }
};
</script>

<style>
.prose {
  @apply text-gray-800;
}

.prose h1 {
  @apply text-3xl font-bold mb-4;
}

.prose h2 {
  @apply text-2xl font-bold mb-3 mt-6;
}

.prose h3 {
  @apply text-xl font-bold mb-3 mt-6;
}

.prose p {
  @apply mb-4 leading-relaxed;
}

.prose img {
  @apply rounded-lg my-6;
}

.prose a {
  @apply text-blue-600 hover:text-blue-800;
}

.prose code {
  @apply bg-gray-100 px-1 py-0.5 rounded;
}

.prose pre {
  @apply bg-gray-100 p-4 rounded-lg overflow-x-auto;
}
</style>
